package com.taplinker.client.im.rpc;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import com.taplinker.client.App;
import com.taplinker.client.AppConfigFactory;
import com.taplinker.client.im.domain.ImDataCenter;
import com.taplinker.client.im.rpc.body.Cmd002Rep;
import com.taplinker.client.im.rpc.body.Cmd002Req;
import com.taplinker.core.rpc.Result;
import com.taplinker.core.util.json.JsonUtil;
import com.ti.winona.ConstantValue;
import com.ti.winona.ui.LoginActivity;
import com.ti.winona.ui.MainActivity;
import com.ti.winona.util.SharedPreferencesUtil;
import com.ti.winona.widget.LoadingDialog;

public class Cmd002 extends SimpleSocketCommand<Cmd002Req> {
	
	private Context mContext;
	private LoadingDialog mDialog;
	
	public Cmd002(Context context, LoadingDialog dialog) {
		mContext = context;
		mDialog = dialog;
		
		body = new Cmd002Req();
		body.setOs("Android");
		body.setDeviceToken(AppConfigFactory.getInstance().getUserInfo().getToken());
	}
	
	@Override
	public void yes(Result result) {
		if (mDialog != null) {
			mDialog.dismiss();
		}
		Cmd002Rep rep = (Cmd002Rep) JsonUtil.jsonToObject(((IMMessageResponse) result.object).getMessage().getBody(), Cmd002Rep.class);
		ImDataCenter.getInstance().setPriNum(rep.getPriNumbers());
//		ImDataCenter.getInstance().setPubNum(rep.getPubNumbers());
		ImDataCenter.getInstance().setCrmNum(rep.getCustomers());
		
		AppConfigFactory.getInstance().getUserInfo().setImToken(rep.getServiceToken());
		
		// 保存ServiceToken
		saveServiceToken(rep.getServiceToken());
		
		((Activity) mContext).startActivity(new Intent(mContext, MainActivity.class));
		((Activity) mContext).finish();
		new Cmd104("APP", true, "user").execute();
	}

	@Override
	protected String getCommand() {
		return "002";
	}
	
	@Override
	public void no(Result result) {
		super.no(result);
		if (mDialog != null) {
			mDialog.dismiss();
		}
		mContext.startActivity(new Intent(mContext, LoginActivity.class));
		App.showToast("登陆失败, 请重试!");
	}
	
	private void saveServiceToken(String serviceToken) {
		SharedPreferencesUtil.putString(mContext, ConstantValue.sharedpreferences.SHARED_NAME, 
				ConstantValue.sharedpreferences.SERVICE_TOKEN, serviceToken);
	}

}
